package com.hlpedu.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hlpedu.mapper.EmployeeMapper;
import com.hlpedu.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;

@Controller
public class EmployeeController {
    //自动装配
    @Autowired
    EmployeeMapper employeeMapper;
    //根据指定id删除员工信息
    @DeleteMapping("employee/{id}")
    public String delete(@PathVariable Integer id){
        employeeMapper.deleteEmp(id);
        return "redirect:/employee";
    }
    //更新记录
    //更新记录第二步：接收前端表单对象，实现数据修改
//    @RequestMapping(value = "employee",method = RequestMethod.PUT)
    @PutMapping("employee")
    public String updateEmp(Employee employee){
        //调用save方法实现数据修改
        employeeMapper.saveEmp(employee);
        //通过重定向实现页面跳转
        return "redirect:/employee";
    }
    //更新记录第一步：根据页面传递的id更新员工信息，并封装数据返回给编辑页面
    @GetMapping("employee/{id}")
    public String getEmpById(@PathVariable Integer id,Model model){
        Employee employee = employeeMapper.queryEmpById(id);
        model.addAttribute("employeeList",employee);
        //通过转发实现页面跳转
        return "employee_edit";
    }
    //新增记录
    @PostMapping("employee")
    public String addEmp(Employee employee){
        System.out.println(employee);
        employeeMapper.saveEmp(employee);
        //重定向
        return "redirect:/employee";
    }
    //点击页面中的添加超链接，跳转页面到employee_edit.jsp
    @RequestMapping("/toAdd")
    public String toAdd(){
        return "employee_edit";
    }
    //根据指定id查询用户信息
    @GetMapping("queryEmp/{id}")
    public String findEmpById(@PathVariable Integer id,Model model){
        Employee employee = employeeMapper.queryEmpById(id);
        //将Java对象转换为json字符串
        String json = JSON.toJSONString(employee);
        model.addAttribute("employeeList",json);
        return "employee_list";
    }
    //完成页面查询所有员工信息
    @RequestMapping("employee")
    public String findAllEmp(Model model){
        Collection<Employee> employeeList = employeeMapper.queryAllEmp();
        //employeeList.forEach(employee -> System.out.println(employee));
        //将集合数据转换为json字符串，再将json字符串转换为json格式的数组
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(employeeList));
        model.addAttribute("employeeList",jsonArray);
        return "employee_list";
    }
    //点击进入员工管理系统超链接进入首页
    //@RequestMapping("/toIndex")
    @GetMapping("/toIndex")
    public String toIndex(){
        return "welcome";
    }
}